$(function() {
  var hideDelay = 500;
  var ID;
  var hideTimer = null;
  var container = $('<div id="tooltip">'
    + '<table border="0" cellspacing="0" cellpadding="0" align="center" class="tooltip">'
    + '<tr>'
    + '   <td><div id="tooltipContent"></div></td>'
    + '   <th style="background-position:right top;"></th>'
    + '</tr>'
    + '<tr>'
    + '   <th style="background-position:left bottom;"></th>'
    + '   <th style="background-position:right bottom;"></th>'
    + '</tr>'
    + '</table>'
  + '</div>');
  $('body').append(container);
  $('.tip').live('mouseover', function() {
    var settings = $(this).attr('rel').split(',');
    var type = settings[0];
    ID = settings[1];
    if (ID == '') return;
    if (hideTimer) clearTimeout(hideTimer);
    var pos = $(this).offset();
    var width = $(this).width();
    container.css({
      left: (pos.left + width) + 'px',
      top: pos.top - 5 + 'px'
    });
    $('#tooltipContent').html('<span style="color:#fff;">Loading...</span>');
    $.ajax({
      type: 'GET',
      url: '',
      data: 'act=tip&type=' + type + '&id=' + ID,
      success: function(data) {
        $('#tooltipContent').html(data);
      }
    });
    container.css('display', 'block');
  });

  $('.tip').live('mouseout', function() {
    if (hideTimer) clearTimeout(hideTimer);
    hideTimer = setTimeout(function() {
      container.css('display', 'none');
    }, hideDelay);
  });

  $('#tooltipContent').mouseover(function() {
    if (hideTimer) clearTimeout(hideTimer);
  });

  $('#tooltipContent').mouseout(function() {
    if (hideTimer) clearTimeout(hideTimer);
    hideTimer = setTimeout(function() {
      container.css('display', 'none');
    }, hideDelay);
  });

});